package com.zerui.manager.app.accessauthpersonnel.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zerui.cola.dto.Response;
import com.zerui.manager.app.access.AuthTaskManager;
import com.zerui.manager.accessauthdevice.domainservice.AccessAuthDeviceRepository;
import com.zerui.manager.accessauthpersonnel.AccessAuthPersonnel;
import com.zerui.manager.accessauthpersonnel.domainservice.AccessAuthPersonnelRepository;
import com.zerui.manager.web.cmd.AccessAuthPersonnelBindCmd;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author wh
 * @create_time 2023-08-30 14:32
 */
@Component
@CatchAndLog
public class AccessAuthPersonnelAddCmdExe {

    @Resource
    private AccessAuthPersonnelRepository accessAuthPersonnelRepository;
    @Resource
    private AccessAuthDeviceRepository accessAuthDeviceRepository;
    @Resource
    private AuthTaskManager authTaskManager;

    public Response execute(AccessAuthPersonnelBindCmd cmd) {
        List<Long> ids = cmd.getPersonnelIds();
        List<AccessAuthPersonnel> accessAuthPersonnelList = accessAuthPersonnelRepository.getByPersonnelIds(ids);
        if(CollectionUtils.isNotEmpty(accessAuthPersonnelList)){
            List<Long> existIds = accessAuthPersonnelList.stream().map(AccessAuthPersonnel::getPersonnelId).collect(Collectors.toList());
            ids.removeAll(existIds);
        }
        if(CollectionUtils.isNotEmpty(ids)){
            List<AccessAuthPersonnel> personals = new ArrayList<>();
            ids.forEach(e-> personals.add(AccessAuthPersonnel.builder()
                    .accessAuthId(cmd.getAccessAuthId())
                    .personnelId(e)
                    .createTime(LocalDateTime.now())
                    .build()));
            accessAuthPersonnelRepository.addBatch(personals);
            // 下发 门禁权限操作
            Long taskId = accessAuthDeviceRepository.devicesDistributePermissionsByPersonals(cmd.getAccessAuthId(), ids);
            if (taskId > 0) {
                authTaskManager.startAuthTask(taskId); // 加入任务执行
            }
        }
        return Response.buildSuccess();
    }
}
